package com.yjd.back.settlement;

import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.enums.StagesStatusEnum;
import com.yjd.comm.merchant.enums.MerchantFundsTypeEnum;
import com.yjd.comm.order.service.IOrderService;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.repayment.dto.RepaymentClearDto;
import com.yjd.comm.repayment.service.IRepaymentClearService;
import com.yjd.comm.settlement.model.ClearDayMerchantModel;
import com.yjd.comm.settlement.model.SettlementDetailModel;
import com.yjd.comm.settlement.service.IClearDayDetailService;
import com.yjd.comm.settlement.service.IClearDayMerchantService;
import com.yjd.comm.settlement.service.IMerchantSettlementService;
import com.yjd.comm.util.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 商户结算处理
 * Created by yangchangyan on 2017/8/25.
 */
@Scope("prototype")
@Controller
@RequestMapping("/merchant")
public class ClearDayMerchantControl extends BaseControl {

    /**
     * 结算列表
     * Created by yangchangyan on 2017/8/25.
     */
    @RequestMapping(value = "/settlement/list")
    public String orderSettlement(String startDate, String endDate) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("sort", "clear_date desc");

        if(StringUtil.isNotEmpty(startDate)){
            paramMap.put("clear_date_gte", Integer.valueOf(startDate.replace("-", "")));
        }
        if(StringUtil.isNotEmpty(endDate)){
            paramMap.put("clear_date_lte", Integer.valueOf(endDate.replace("-", "")));
        }

        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.clearDayMerchantService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/merchant/settlement/list"));

        Map<Long, String> orgIdAndName = organizationService.allOrgAndName();
        ClearDayMerchantModel cdmm = null;
        Double clear_price = 0D;
        for (Object obj : pager.getPagerModel().getDataList()) {
            cdmm = (ClearDayMerchantModel)obj;
            // 还款的结算金额 =（还款金额+罚息金额）-平台管理费-逾期管理费
            clear_price = ArithUtil.add(cdmm.getRepayment_price(), cdmm.getOverdue_price());
            clear_price = ArithUtil.subs(clear_price, cdmm.getManage(), cdmm.getManage_overdue());
            cdmm.getStrMap().put("loan_price", ArithUtil.add(cdmm.getLoan_price(), clear_price));
            cdmm.getStrMap().put("org_name", orgIdAndName.get(cdmm.getOrg_id()));
            cdmm.getStrMap().put("create_time", DateUtil.timestampToDateString(cdmm.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        }

        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);
        request.setAttribute("orgids", organizationService.allOrgAndName());

        return "merchantClearDay.list";
    }

    /**
     * 结算明细
     * Created by yangchangyan on 2017/8/25.
     */
    @RequestMapping(value = "/settlement/detail")
    public String detail(String clear_date) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        ClearDayMerchantModel cdmm = this.clearDayMerchantService.getModelOne(paramMap, DbWREnums.READ);
        if(null == cdmm){
            FrameUtil.throwBaseException1("信息不存在");
        }

        // 还款的结算金额 =（还款金额+罚息金额）-平台管理费-逾期管理费
        Double clear_price = ArithUtil.add(cdmm.getRepayment_price(), cdmm.getOverdue_price());
        clear_price = ArithUtil.subs(clear_price, cdmm.getManage(), cdmm.getManage_overdue());
        cdmm.getStrMap().put("loan_price", ArithUtil.add(cdmm.getLoan_price(), clear_price));

        paramMap.put("sort", "clear_date desc");
        List<SettlementDetailModel> sdms = clearDayDetailService.querySettlementDetail(paramMap, DbWREnums.READ);
        for(SettlementDetailModel sdm : sdms){
            sdm.getStrMap().put("clear_price", sdm.getClear_price());
            sdm.getStrMap().put("type", MerchantFundsTypeEnum.parse(sdm.getType()).getLabel());
            sdm.getStrMap().put("order_create_time", DateUtil.timestampToDateString(sdm.getOrder_create_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            sdm.getStrMap().put("order_status", StagesStatusEnum.parse(sdm.getOrder_status()).getLabel());
            sdm.getStrMap().put("create_time", DateUtil.timestampToDateString(sdm.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            sdm.getStrMap().put("repayment_price","-");
            sdm.getStrMap().put("overdue_price","-");
            sdm.getStrMap().put("manage","-");
            sdm.getStrMap().put("manage_overdue","-");
        }

        cdmm.getStrMap().put("create_time", DateUtil.timestampToDateString(cdmm.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        if(null != sdms && sdms.size() > 0){
            cdmm.getStrMap().put("org_name", sdms.get(0).getOrg_name());
        }else{
            OrganizationModel organizationModel =  organizationService.getModelById(cdmm.getOrg_id(),DbWREnums.READ);
            cdmm.getStrMap().put("org_name", organizationModel.getOrg_name());
        }

        // 查询VIP订单还款记录
        List<RepaymentClearDto> repaymentClearDtos = repaymentClearService.queryRepaymentInfo(paramMap, DbWREnums.WRITE);
        if(null != repaymentClearDtos && repaymentClearDtos.size() > 0){
            SettlementDetailModel sdm = null;
            for(RepaymentClearDto rcd:repaymentClearDtos){
                sdm = new SettlementDetailModel();
                sdm.setOrder_no(rcd.getOrder_no());
                sdm.setId_name(rcd.getId_name());
                sdm.setCreate_time(rcd.getCreate_time());
                sdm.getStrMap().put("type", MerchantFundsTypeEnum.REPAYMENT.getLabel());
                sdm.getStrMap().put("order_create_time", DateUtil.timestampToDateString(rcd.getOrder_create_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
                sdm.getStrMap().put("order_status", StagesStatusEnum.REPAYMENTING.getLabel());
                sdm.getStrMap().put("create_time", DateUtil.timestampToDateString(rcd.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
                sdm.getStrMap().put("repayment_price",rcd.getRepayment_price());
                sdm.getStrMap().put("overdue_price",rcd.getOverdue_price());
                sdm.getStrMap().put("manage",rcd.getManage());
                sdm.getStrMap().put("manage_overdue",rcd.getManage_overdue());

                // 还款的结算金额 =（还款金额+罚息金额）-平台管理费-逾期管理费
                sdm.setClear_price(FeeCalcUtil.calcSettlementPrice(rcd));
                sdm.getStrMap().put("clear_price", sdm.getClear_price()+"（含利息"+rcd.getInterest_price()+"）");

                sdms.add(sdm);
            }
        }

        // 按创建时间排序，正序
        Collections.sort(sdms, new Comparator<SettlementDetailModel>() {
            @Override
            public int compare(SettlementDetailModel sdm1, SettlementDetailModel sdm2) {
                if(sdm1.getCreate_time() > sdm2.getCreate_time()){
                    return 1;
                }
                return -1;
            }
        });

        request.setAttribute("merchant", cdmm);
        request.setAttribute("details", sdms);
        request.setAttribute("maps", paramMap);

        return "merchantClearDay.detail";
    }

    /**
     * 确认结算(线下打款完成后，确认平台内的结算单状态)
     * Created by yangchangyan on 2017/8/25.
     */
    @RequestMapping(value = "/settlement/confirm")
    public void confirm(Long id) throws Exception {
        ClearDayMerchantModel clearDayModel = this.clearDayMerchantService.getModelById(id, DbWREnums.READ);
        if(null == clearDayModel){
            FrameUtil.throwBaseException1("结算单不存在！");
        }
        ClearDayMerchantModel model = new ClearDayMerchantModel();
        model.setStatus(1);
        model.setId(clearDayModel.getId());
        model.setUpdate_time(FrameUtil.getTime());
        clearDayMerchantService.update(model);
        this.successMsg(ServletUtil.getUrl("/merchant/settlement/list"),"已确认结算");
    }

    /**
     * 生成商户结算单
     * Created by yangchangyan on 2017/8/25.
     */
    @RequestMapping(value = "/settlement/generate")
    public String generateSettlement(String startDate, String endDate) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        Long org_id = null;
        if(StringUtil.isNotEmpty(paramMap.get("org_id"))){
            org_id = Long.valueOf(paramMap.get("org_id").toString());
        }

        Long startTime = FrameUtil.getTime();
        if(StringUtil.isNotEmpty(startDate)){
            startTime = DateUtil.dateStringToTimestamp(startDate, DateUtil.PATTERN_yyyy_MM_dd);
        }

        Long endTime = FrameUtil.getTime();
        if(StringUtil.isNotEmpty(endDate)){
            endTime = DateUtil.dateStringToTimestamp(endDate, DateUtil.PATTERN_yyyy_MM_dd);
        }

        if(startTime > endTime){
            FrameUtil.throwBaseException1("日期不合法");
        }

        merchantSettlementService.settlementAll(org_id, startTime, endTime);

        return "redirect:/merchant/settlement/list.action";
    }

    @Resource
    private IRepaymentClearService repaymentClearService;

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private IOrderService orderService;

    @Resource
    private IClearDayMerchantService clearDayMerchantService;

    @Resource
    private IClearDayDetailService clearDayDetailService;

    @Resource
    private IMerchantSettlementService merchantSettlementService;

}
